//
//  RHDeviceReportVC.m
//  RuiHeApp
//
//  Created by Yan Chen on 2024/11/15.
//

#import "RHDeviceReportVC.h"
#import "RHReportStatisticsCell.h"
#import "RHReportHeaderView.h"
#import "RHReportDataCell.h"
#import "RHDevReporSetVC.h"
#import "RHDeviceListViewController.h"
#import "RHReportConfigModel.h"
#import "WSDatePickerView.h"
#import "RHReportDataModel.h"
#import "RHChoiceTypeView.h"

@interface RHDeviceReportVC ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic ,strong) UITableView *tableView;

@property (nonatomic, assign) NSInteger typeIndex;

@property (nonatomic, strong) RHReportHeaderView *headerView;

@property (nonatomic, strong) RHDeviceModel *curDevice;

@property (nonatomic, strong) NSArray *reportDataArr;

@end

@implementation RHDeviceReportVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"设备报表".rh_localized;
    self.view.backgroundColor = CFTabViewBgColor;

    [self setupUI];
  
    [self getFirstDeviceList];
   
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
}

-(void)setupUI
{
    UIButton *addButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0,40, 64)];
    [addButton setImage:[UIImage imageNamed:@"kwt_mine_set"] forState:UIControlStateNormal];
    [addButton setBackgroundColor:UIColor.clearColor];
    [addButton setTitleColor:[UIColor orangeColor] forState:UIControlStateNormal];
    [addButton.titleLabel setFont:[UIFont systemFontOfSize:16]];
    [addButton setContentHorizontalAlignment:UIControlContentHorizontalAlignmentRight];
    [addButton addTarget:self action:@selector(reportSet) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *rightBarBtn = [[UIBarButtonItem alloc] initWithCustomView:addButton];
    self.navigationItem.rightBarButtonItem = rightBarBtn;
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    [_tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    [_tableView setBackgroundColor:UIColor.clearColor];
    [_tableView setDelegate:self];
    [_tableView setDataSource:self];
    _tableView.tableHeaderView = [self headerView];
    
    [_tableView registerClass:[RHReportStatisticsCell class] forCellReuseIdentifier:@"RHReportStatisticsCell"];
    [_tableView registerClass:[RHReportDataCell class] forCellReuseIdentifier:@"RHReporDataCell"];
   

    
    [self.view addSubview:_tableView];
    
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.insets(UIEdgeInsetsZero);
    }];
    kWeakSelf;
    [_tableView addHeaderRefresh:^{
        if (weakSelf.curDevice) {
            [weakSelf getDeviceReportDataList];
        }else{
            [weakSelf.tableView endHeaderRefresh];
        }
    }];
    
    if (@available(iOS 15.0, *)) {
        _tableView.sectionHeaderTopPadding = 0;
    }
}

-(void)reportSet
{
    kWeakSelf;
    RHDevReporSetVC *setVC = [[RHDevReporSetVC alloc]init];
    [self.navigationController pushViewController:setVC animated:YES];
}

#pragma mark ------ 报表配置
-(void)reportConfigQurey
{
    [RHReportConfigModel startGetWithCompletionAPIKey:H_deviceReportConfigQuery argument:@{@"type":@(1)} requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        if (resultModel.code == 200) {
            RHReportConfigModel *configModel = resultModel.data;
            self.curDevice = self.curDevice;
        }
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        
    }];
}

#pragma mark ----- 获取用户设备列表 ------
-(void)getFirstDeviceList
{
    NSString *status = @"";

    
    [QMUITips showLoadingInView:self.view];
    NSDictionary *para = @{@"userId":@([PrivateMange share].currentUser.userId),
                           @"pageNum":@(1),
                           @"pageSize":@(1),
                           @"status":@"",
                           @"deviceId":@""
    };
    [RHDeviceModel startGetWithCompletionAPIKey:H_deviceList argument:para requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        if(resultModel.code == 200){
            NSArray *devices = resultModel.data;
            self.curDevice = [devices firstObject];
            if (self.curDevice) {
                self.headerView.devLab.text = ValidNullDataToString(self.curDevice.deviceId, @"--");
                [self getDeviceReportDataList];
            }
            
        }
        
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
           
    }];
}


#pragma mark ----- 获取报表数据 ------
-(void)getDeviceReportDataList
{
    if (!self.curDevice) {
        return;
    }
    [QMUITips showLoadingInView:kAppWindow];
    NSDate *date = [NSDate dateWithString:self.headerView.dateLab.text formatString:@"yyyy-MM-dd"];
    NSDate *begin_date = [NSDate dateWithYear:date.year month:date.month day:date.day hour:0 minute:0 second:0];
    NSDate *end_date = [NSDate dateWithYear:date.year month:date.month day:date.day hour:23 minute:59 second:59];
    
    NSString *begin_time = [NSString stringWithFormat:@"%zd",(NSInteger)[begin_date timeIntervalSince1970]*1000];
    NSString *end_time = [NSString stringWithFormat:@"%zd",(NSInteger)[end_date timeIntervalSince1970]*1000];
    
    NSTimeZone *curZone = [NSTimeZone localTimeZone];
    NSDictionary *para = @{@"pageNum":@(1),
                           @"pageSize":@(500),
                           @"startTime":begin_time,
                           @"endTime":end_time,
                           @"deviceId":self.curDevice.deviceId,
                         
                           @"timeZone":curZone.name};
    
    [RHReportDataModel startWithCompletionAPIKey:H_deviceReportDataList argument:para requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        [self.tableView endHeaderRefresh];
        if (resultModel.code == 200) {
            NSArray *dataArr = request.responseJSONObject[@"data"][@"data"];
            self.reportDataArr = [NSArray yy_modelArrayWithClass:[RHReportDataModel class] json:dataArr];
            [self.tableView reloadData];
        }
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        [self.tableView endHeaderRefresh];
    }];
}
#pragma mark - UITableViewDelegate,UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
   
   return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{

    return self.reportDataArr.count;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return UITableViewAutomaticDimension;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
   
    return UITableViewAutomaticDimension;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    if (section == 0) {
        UIView *headerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kUI_WINDOW_W, 125)];
        headerView.backgroundColor = CFTabViewBgColor;
        
        QMUILabel *titleLab = [QMUILabel labelWithText:@"电量指标".rh_localized font:kSYSTEMFONT(16) textColor:kCOLOR_HEX(@"#171A1D")];
        [headerView addSubview:titleLab];
        [titleLab mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_offset(15);
            make.top.mas_offset(15);
        }];
        //日充放电量 累计充放电量
        UIView *timeView = [self createTimeView];
        timeView.backgroundColor = CFTabViewBgColor;
        [headerView addSubview:timeView];
        [timeView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_offset(0);
            make.right.mas_offset(0);
            make.top.equalTo(titleLab.mas_bottom);
        }];
        
        //下面的标签
        UIView *bottomView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kUI_WINDOW_W-30, 100)];
        [bottomView setBackgroundColor:UIColor.whiteColor];
        [bottomView setTopBorder];
        [headerView addSubview:bottomView];
        [bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(timeView.mas_bottom).offset(0);
            make.left.mas_offset(15);
            make.right.mas_offset(-15);
            make.bottom.mas_offset(0);

        }];
        
        QMUILabel *powerTitleLab = [QMUILabel labelWithFont:kBOLDSYSTEMFONT(16) textColor:kCOLOR_HEX(@"3F4443")];
        powerTitleLab.text = self.typeIndex == 0?@"日买卖电量".rh_localized:@"累计买卖电量".rh_localized;
//        powerTitleLab.numberOfLines = 2;
        powerTitleLab.textAlignment = NSTextAlignmentLeft;
        [bottomView addSubview:powerTitleLab];
        
        [powerTitleLab mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_offset(15);
            make.right.mas_offset(-15);
            make.top.mas_offset(15);
        }];
        
        UIView *line = kView;
        line.backgroundColor = kCOLOR_HEX_A(@"#7E868E",0.2);
        [bottomView addSubview:line];
        [line mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_offset(15);
            make.right.mas_offset(-15);
            make.height.offset(1);
            make.top.equalTo(powerTitleLab.mas_bottom).offset(15);
        }];
        
        UIView *optionView = kView;
        optionView.backgroundColor = CFTabViewBgColor;
        [bottomView addSubview:optionView];
        [optionView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_offset(12);
            make.right.mas_offset(-12);
            make.top.equalTo(line.mas_bottom).offset(10);
            make.height.offset(35);
            make.bottom.mas_offset(-3);
        }];
        
        NSString *powerTitle = [NSString stringWithFormat:@"%@(%%)",@"soc"];
       
        NSArray *titles = @[@"时段".rh_localized,
                            [NSString stringWithFormat:@"%@(kWh)",@"买电量".rh_localized],
                            [NSString stringWithFormat:@"%@(kWh)",@"卖电量".rh_localized],
                            powerTitle];
      
        CGFloat labWidth = (kUI_WINDOW_W-30-20)/titles.count;
        [titles enumerateObjectsUsingBlock:^(NSString*  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            QMUILabel *lab = [QMUILabel labelWithFont:kSYSTEMFONT(13) textColor:kCOLOR_HEX(@"#171A1D")];
            lab.text = obj;
            lab.adjustsFontSizeToFitWidth = YES;
            lab.minimumScaleFactor = 0.8;
            lab.numberOfLines = 2;
            [optionView addSubview:lab];
            [lab mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.mas_offset(idx*labWidth);
                make.centerY.mas_offset(0);
                make.width.offset(labWidth);
            }];
        }];
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [headerView setNeedsLayout];
            [headerView layoutIfNeeded];
            NSLog(@"--->header frame:%@",NSStringFromCGRect(headerView.frame));
            NSLog(@"--->bottom frame:%@",NSStringFromCGRect(bottomView.frame));
        });
        
        return headerView;
    }
    return nil;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    if (self.reportDataArr.count==0) {
        return 8;
    }
    return 0;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    if (self.reportDataArr.count==0) {
        return [UIView createSectionFooterView:8];
    }
    return nil;;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    RHReportDataCell *dataCell = [tableView dequeueReusableCellWithIdentifier:@"RHReporDataCell"];
    RHReportDataModel *model = [self.reportDataArr safeObjectAtIndex:indexPath.row];
    RHReportDataModel *lastModel = [self.reportDataArr safeObjectAtIndex:indexPath.row + 1];
    [dataCell setModel:model lastModel:lastModel type:self.typeIndex];
    [dataCell setMiddleBorder];
    if (indexPath.row == self.reportDataArr.count-1) {
        [dataCell.bgView setBottomBorder];
    }else{
        [dataCell.bgView setMiddleBorder];
    }
    return dataCell;
   
}


-(UIView*)headerView{
    if (!_headerView) {
        _headerView = [[RHReportHeaderView alloc]init];
        _headerView.backgroundColor = CFTabViewBgColor;
        kWeakSelf;
        _headerView.clickBlock = ^(NSInteger index) {
            if (index == 0) {
                RHDeviceListViewController *devVC = [[RHDeviceListViewController alloc]init];
                devVC.titleStr  = @"选择设备".rh_localized;
                devVC.devReportSelectBlock = ^(RHDeviceModel * _Nonnull device) {
                    weakSelf.headerView.devLab.text = device.deviceId;
                    weakSelf.curDevice = device;
                    [weakSelf getDeviceReportDataList];
                };
                [weakSelf.navigationController pushViewController:devVC animated:YES];
               
            }
           
            if (index == 1) {
             
                WSDatePickerView *datePickerV = [[WSDatePickerView alloc] initWithDateStyle:DateStyleShowYearMonthDay CompleteBlock:^(NSDate *selectDate) {
                    weakSelf.headerView.dateLab.text = [selectDate stringWithFormat:@"yyyy-MM-dd"];
                    [weakSelf getDeviceReportDataList];
                }];
                datePickerV.dateLabelColor = FontColor(@"#3ECE80");//年-月 颜色
                datePickerV.datePickerColor = UIColorBlack;//滚轮日期颜色
                datePickerV.doneButtonColor = UIColor.blackColor;//确定按钮的颜色
                datePickerV.maxLimitDate = [NSDate date];
                datePickerV.minLimitDate = [NSDate dateWithYear:[NSDate date].year-10 month:[NSDate date].month day:[NSDate date].day hour:[NSDate date].hour minute:[NSDate date].minute second:[NSDate date].second];
                
                [datePickerV show];
            }
        };
        
        _headerView.dateLab.text = [NSDate getCurrentTimeStringWithFormat:@"yyyy-MM-dd"];
        
    }
    
    return _headerView;
}


-(UIView*)createTimeView
{
    UIView *bgView = [[UIView alloc]init];
    bgView.backgroundColor = UIColor.whiteColor;

    __block QMUIButton *lastItem;
    __block CGFloat btnWidth = (kUI_WINDOW_W - 45)/2;
    NSArray *timeArr = @[@"日买卖电量".rh_localized,@"累计买卖电量".rh_localized];
    [timeArr enumerateObjectsUsingBlock:^(NSString * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        QMUIButton *btn = [[QMUIButton alloc]init];
        [btn setTitle:obj forState:UIControlStateNormal];
        btn.titleLabel.font = kSYSTEMFONT(14);
        btn.titleLabel.numberOfLines = 2;
        [btn setTitleColor:[UIColor colorWithHexString:@"3F4443" alpha:0.8] forState:UIControlStateNormal];
        btn.backgroundColor = kCOLOR_HEX(@"F6F8FA");
        btn.layer.cornerRadius = 8;
        btn.userInteractionEnabled = YES;
        [btn setBackgroundColor:kCOLOR_HEX(@"FFFFFF")];
        [bgView addSubview:btn];
        
        [btn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.width.offset(btnWidth);
            make.height.offset(45);
            if(lastItem){
                if (idx%2==0) {//换行
                    make.left.mas_offset(15);
                    make.top.equalTo(lastItem.mas_bottom).offset(15);
                }else{
                    make.left.equalTo(lastItem.mas_right).offset(15);
                    make.top.equalTo(lastItem);
                }
                
            }else{
                make.left.mas_offset(15);
                make.top.mas_offset(15);
            }
        }];
     
        lastItem = btn;
        kWeakSelf;
        [[btn rac_signalForControlEvents:UIControlEventTouchUpInside]subscribeNext:^(__kindof UIControl * _Nullable x) {
            weakSelf.typeIndex = idx;
            [weakSelf.tableView reloadData];
        }];
        
        [RACObserve(self, typeIndex) subscribeNext:^(id  _Nullable x) {
            if([x integerValue] == idx){
                [btn setTitleColor:[UIColor colorWithHexString:@"ffffff" alpha:1] forState:UIControlStateNormal];
                [btn setBackgroundColor:CMainColorGreen];
                [btn rounded:8 width:1 color:CMainColorGreen];
            }else{
                [btn setTitleColor:[UIColor colorWithHexString:@"3F4443" alpha:0.6] forState:UIControlStateNormal];
                [btn setBackgroundColor:UIColor.whiteColor];
                [btn rounded:8 width:1 color:kBorderColor];
            }
        }];
   
    }];
    [lastItem mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_offset(-15);
    }];
    return bgView;
}
@end
